package com.tanhua.app.service;

import cn.hutool.core.collection.CollectionUtil;
import com.tanhua.api.db.UserInfoApi;
import com.tanhua.api.mongo.RecommentApi;
import com.tanhua.api.mongo.VisitorsApi;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mogo.Visitors;
import com.tanhua.domain.vo.UserHolder;
import com.tanhua.domain.vo.VisitorsVo;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class MovementsService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Reference
    private VisitorsApi visitorsApi;

    @Reference
    private UserInfoApi userInfoApi;

    @Reference
    private RecommentApi recommentApi;

    //查找访客
    public ResponseEntity visitors() {

        // 查询redis获取当前用户的上次登录时间（首页）如果没有查询到(time=null),记录当前用户登录时间
        Long userId = UserHolder.getUser().getId();
        String time = stringRedisTemplate.opsForValue().get("visitors_user_" +userId);

        // 查到了---拿着时间去历史访客表中做时间的对比 获取到访客的id
       List<VisitorsVo> voList=new ArrayList();
        if(time!=null){
            List<Visitors> list=visitorsApi.findvisitorsList(userId,Long.parseLong(time));
            // 根据访客的id获取访客信息
            if(CollectionUtil.isNotEmpty(list)){
                for (Visitors visitors : list) {
                    UserInfo userInfo = userInfoApi.findUserInfo(visitors.getVisitorUserId());

                    // 封装vo返回
                    VisitorsVo vo = new VisitorsVo();
                    vo.setUserInfo(userInfo);
                    //查询当前登录用户和访客之间的缘分值 recommend_user
                    Long score = recommentApi.findScore(userId, visitors.getVisitorUserId());
                    if(score==null){//不设缘分值假数据可能会空指针异常
                        score = 99L;
                    }
                    vo.setFateValue(score);
                    voList.add(vo);
                }
            }

        }

        // 将当前时间作为登录用户最新登录时间 覆盖redis  key:当前登录用户  value:当前时间
        stringRedisTemplate.opsForValue().set("visitors_user_"+ UserHolder.getUser().getId(),System.currentTimeMillis()+"");

        return ResponseEntity.ok(voList);

    }
}
